<template>
  <div ref="terminalContainer" class="terminal-container"></div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue'
import { Terminal } from 'xterm'
import { FitAddon } from 'xterm-addon-fit'
import 'xterm/css/xterm.css'

const props = defineProps({
  serverId: { type: Number, required: true },
  serverIp: { type: String, required: true },
  serverPort: { type: Number, required: true },
  username: { type: String, required: true },
  password: { type: String, default: '' }, // 密码可能是空的
})

const terminalContainer = ref<HTMLElement | null>(null)
let term: Terminal | null = null
let fitAddon: FitAddon | null = null
let websocket: WebSocket | null = null

const initTerminal = () => {
  if (!terminalContainer.value) return

  term = new Terminal({
    fontSize: 16,
    fontFamily: 'Consolas, "Courier New", monospace',
    cursorBlink: true,
    scrollback: 1000,
    theme: {
      background: '#1e1e1e',
      foreground: '#d4d4d4',
      cursor: '#d4d4d4',
      selectionBackground: '#656565',
      black: '#000000',
      red: '#e06c75',
      green: '#98c379',
      yellow: '#e5c07b',
      blue: '#61afef',
      magenta: '#c678dd',
      cyan: '#56b6c2',
      white: '#abb2bf',
      brightBlack: '#5c6370',
      brightRed: '#e06c75',
      brightGreen: '#98c379',
      brightYellow: '#e5c07b',
      brightBlue: '#61afef',
      brightMagenta: '#c678dd',
      brightCyan: '#56b6c2',
      brightWhite: '#ffffff',
    }
  })

  fitAddon = new FitAddon()
  term.loadAddon(fitAddon)

  nextTick(() => {
    if (terminalContainer.value && term && fitAddon) {
      term.open(terminalContainer.value);
      fitAddon.fit();

      // Call fitTerminal once after initialization
      fitTerminal();
    }
  });

  term.onData((data) => {
    if (websocket && websocket.readyState === WebSocket.OPEN) {
      websocket.send(data)
    }
  })

  window.addEventListener('resize', fitTerminal)
}

const initWebSocket = () => {
  const baseApi = import.meta.env.VITE_BASE_API.replace('http', 'ws')
  const token = localStorage.getItem('token') || ''; // 获取 Sa-Token
  const wsUrl = `${baseApi}/ws/terminal?serverId=${props.serverId}&token=${token}` // 将 token 附加到 URL 中
  console.log("Connecting to WebSocket:", wsUrl);

  websocket = new WebSocket(wsUrl)

  websocket.onopen = () => {
    console.log('WebSocket connected successfully to:', wsUrl);
    term?.write('Connected to server. \r\n')
  }

  websocket.onmessage = (event) => {
    term?.write(event.data)
  }

  websocket.onclose = (event) => {
    console.log('WebSocket closed:', event.code, event.reason, 'URL:', wsUrl);
    term?.write('\r\nDisconnected from server. \r\n')
  }

  websocket.onerror = (error) => {
    console.error('WebSocket error:', error, 'URL:', wsUrl);
    term?.write('\r\nWebSocket error. Please check console for details. \r\n')
  }
}

const fitTerminal = () => {
  if (term && fitAddon) {
    fitAddon.fit();
    term.refresh(0, term.rows - 1);
    // Add console logs for debugging dimensions
    if (terminalContainer.value) {
      console.log('Terminal container dimensions after fit:', {
        width: terminalContainer.value.offsetWidth,
        height: terminalContainer.value.offsetHeight
      });
    }
  }
}

onMounted(() => {
  initTerminal()
  initWebSocket()
})

onUnmounted(() => {
  websocket?.close()
  term?.dispose()
  window.removeEventListener('resize', fitTerminal)
})

watch(() => props.serverId, (newVal, oldVal) => {
  if (newVal !== oldVal && newVal) {
    websocket?.close();
    term?.reset();
    initWebSocket();
  }
});

defineExpose({
  fitTerminal
});
</script>

<style scoped>
.terminal-container {
  width: 100%;
  height: 100%; /* 让终端容器的高度由父级弹窗控制 */
  background-color: #1e1e1e; /* 统一背景色 */
  padding: 15px; /* 增加内边距 */
  box-sizing: border-box;
  overflow: hidden; /* Ensure content overflows within xterm.js, not creating external scrollbars */
}

/* Custom scrollbar styles for webkit browsers if xterm.js allows them (usually not needed) */
/* This section might not apply if xterm.js handles its own scrollbars internally */
.terminal-container::-webkit-scrollbar {
  width: 8px; /* 滚动条宽度 */
  height: 8px; /* 滚动条高度 */
}

.terminal-container::-webkit-scrollbar-track {
  background: #2d2d2d; /* 滚动条轨道背景 */
  border-radius: 4px;
}

.terminal-container::-webkit-scrollbar-thumb {
  background: #888; /* 滚动条滑块颜色 */
  border-radius: 4px;
}

.terminal-container::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8; /* 滚动条滑块悬停颜色 */
}

/* Firefox scrollbar styles */
.terminal-container {
  scrollbar-width: thin; /* "thin" or "auto" */
  scrollbar-color: #888 #2d2d2d; /* 滑块颜色 轨道颜色 */
}
</style>
